<template>
  <div class="analysis-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">
          <el-icon><DataAnalysis /></el-icon>
          数据分析
        </h2>
        <p class="page-description">
          {{ currentProductName }} - 深度分析模块依赖关系和性能数据
        </p>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          :icon="Refresh"
          @click="refreshAnalysis"
          :loading="loading"
        >
          刷新分析
        </el-button>
      </div>
    </div>

    <!-- 分析选项 -->
    <el-card class="analysis-options" shadow="never">
      <el-form :model="analysisForm" :inline="true">
        <el-form-item label="分析类型">
          <el-select
            v-model="analysisForm.type"
            placeholder="选择分析类型"
          >
            <el-option label="依赖关系分析" value="dependency" />
            <el-option label="性能分析" value="performance" />
            <el-option label="内存分析" value="memory" />
          </el-select>
        </el-form-item>
        <el-form-item label="分析深度">
          <el-slider
            v-model="analysisForm.depth"
            :min="1"
            :max="5"
            :step="1"
            show-stops
            style="width: 200px"
          />
          <span class="depth-label">{{ getDepthLabel(analysisForm.depth) }}</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="runAnalysis">开始分析</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 分析结果 -->
    <div class="analysis-results" v-if="modulesStore.currentProduct && modulesStore.currentVersion">
      <!-- 空状态提示 -->
      <div v-if="!modulesStore.hasProducts && !loading" class="empty-state">
        <el-empty description="正在加载产品数据...">
          <el-button type="primary" @click="modulesStore.fetchProducts()">重新加载</el-button>
        </el-empty>
      </div>
  
      <!-- 统计图表 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="analysis-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>模块复杂度分布</span>
                <el-tooltip effect="dark" placement="top" :show-after="500">
                  <template #content>
                    <div class="complexity-tooltip">
                      <h4>复杂度评分说明</h4>
                      <div class="formula">
                        <strong>计算公式：</strong><br/>
                        复杂度 = (依赖数量 × 5) + (符号数量 ÷ 20)
                      </div>
                      <div class="ranges">
                        <div class="range-item">
                          <span class="range-badge low">0-20</span>
                          <span>低复杂度</span>
                        </div>
                        <div class="range-item">
                          <span class="range-badge medium-low">21-40</span>
                          <span>中低复杂度</span>
                        </div>
                        <div class="range-item">
                          <span class="range-badge medium">41-60</span>
                          <span>中等复杂度</span>
                        </div>
                        <div class="range-item">
                          <span class="range-badge medium-high">61-80</span>
                          <span>中高复杂度</span>
                        </div>
                        <div class="range-item">
                          <span class="range-badge high">81-100</span>
                          <span>高复杂度</span>
                        </div>
                      </div>
                      <div class="factors">
                        <div class="factor-item">
                          <el-icon style="color: #409EFF;"><Link /></el-icon>
                          <span>每个依赖 +5 分</span>
                        </div>
                        <div class="factor-item">
                          <el-icon style="color: #67C23A;"><Cpu /></el-icon>
                          <span>每20个符号 +1 分</span>
                        </div>
                      </div>
                      <div class="risk-levels">
                        <div class="risk-item">
                          <span class="risk-badge high-risk">高风险</span>
                          <span>复杂度>80 或 依赖>20</span>
                        </div>
                        <div class="risk-item">
                          <span class="risk-badge medium-risk">中风险</span>
                          <span>复杂度>60 或 依赖>10</span>
                        </div>
                        <div class="risk-item">
                          <span class="risk-badge low-risk">低风险</span>
                          <span>其他情况</span>
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-icon size="16" color="#909399">
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <ComplexityChart />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="analysis-card" shadow="hover">
            <template #header>
              <span>内存使用统计</span>
            </template>
            <MemoryChart />
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细分析表格 -->
      <el-card class="analysis-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>分析报告</span>
            <el-tooltip effect="dark" placement="top" :show-after="500">
              <template #content>
                <div class="analysis-report-tooltip">
                  <h4>分析报告说明</h4>

                  <div class="section">
                    <h5>🔍 数据说明</h5>
                    <ul>
                      <li><strong>数据范围</strong>：分析所有模块（无数量限制）</li>
                      <li><strong>数据来源</strong>：优先使用后端API数据，失败时使用前端智能分析</li>
                      <li><strong>过滤功能</strong>：支持按模块名称、风险等级、复杂度范围进行筛选</li>
                      <li><strong>排序功能</strong>：支持按模块名称、复杂度、内存使用、依赖数排序</li>
                    </ul>
                  </div>

                  <div class="section">
                    <h5>📊 复杂度计算方法</h5>
                    <div class="formula">
                      复杂度 = 20（基础） + 依赖加分 + 大小加分 + 内存加分
                    </div>

                    <div class="factors-grid">
                      <div class="factor-card">
                        <div class="factor-title">依赖数量影响</div>
                        <div class="factor-items">
                          <div class="item">> 平均值×2：+30分</div>
                          <div class="item">> 平均值：+15分</div>
                        </div>
                      </div>

                      <div class="factor-card">
                        <div class="factor-title">文件大小影响</div>
                        <div class="factor-items">
                          <div class="item">> 1MB：+25分</div>
                          <div class="item">> 512KB：+15分</div>
                          <div class="item">> 100KB：+10分</div>
                        </div>
                      </div>

                      <div class="factor-card">
                        <div class="factor-title">内存使用影响</div>
                        <div class="factor-items">
                          <div class="item">> 1MB：+20分</div>
                          <div class="item">> 512KB：+10分</div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="section">
                    <h5>⚠️ 风险等级判断</h5>
                    <div class="risk-criteria">
                      <div class="risk-item">
                        <span class="risk-badge high">高风险</span>
                        <span>依赖数 > 平均值×2 或 复杂度 > 70</span>
                      </div>
                      <div class="risk-item">
                        <span class="risk-badge medium">中风险</span>
                        <span>依赖数 > 平均值 或 复杂度 > 50</span>
                      </div>
                      <div class="risk-item">
                        <span class="risk-badge low">低风险</span>
                        <span>其他情况</span>
                      </div>
                    </div>
                  </div>

                  <div class="section note">
                    <h5>💡 说明</h5>
                    <p>分析报告采用多维度评估算法，综合考虑模块的耦合度（依赖数量）、规模（文件大小）和运行时资源消耗（内存使用），帮助识别系统中的关键模块和潜在风险点。</p>
                  </div>
                </div>
              </template>
              <el-icon size="16" color="#909399">
                <InfoFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>

        <!-- 搜索和过滤工具栏 -->
        <div class="table-toolbar">
          <div class="search-section">
            <el-input
              v-model="tableFilter.keyword"
              placeholder="搜索模块名称..."
              :prefix-icon="Search"
              clearable
              style="width: 250px"
              @input="handleFilter"
            />
            <el-select
              v-model="tableFilter.riskLevel"
              placeholder="风险等级"
              clearable
              style="width: 120px; margin-left: 12px"
              @change="handleFilter"
            >
              <el-option label="高风险" value="高" />
              <el-option label="中风险" value="中" />
              <el-option label="低风险" value="低" />
            </el-select>
            <el-select
              v-model="tableFilter.complexityRange"
              placeholder="复杂度范围"
              clearable
              style="width: 120px; margin-left: 12px"
              @change="handleFilter"
            >
              <el-option label="高 (80-100)" value="high" />
              <el-option label="中 (50-79)" value="medium" />
              <el-option label="低 (0-49)" value="low" />
            </el-select>
          </div>
          <div class="action-section">
            <el-button @click="resetFilter">重置</el-button>
            <div v-if="loadingProgress > 0 && loading" class="progress-section">
              <span class="progress-text">分析进度: {{ loadingProgress }}%</span>
              <el-progress :percentage="loadingProgress" :stroke-width="6" :show-text="false" style="width: 120px;" />
            </div>
          </div>
        </div>

        <el-table
          :data="paginatedAnalysisResults"
          style="width: 100%"
          stripe
          height="600"
          :default-sort="{ prop: 'complexity', order: 'descending' }"
          @sort-change="handleSortChange"
          v-loading="loading"
          element-loading-text="正在分析数据..."
          :element-loading-spinner="Loading"
          :element-loading-background="'rgba(0, 0, 0, 0.8)'"
        >
          <el-table-column prop="module" label="模块名称" min-width="200" sortable />
          <el-table-column prop="complexity" label="复杂度" width="120" sortable>
            <template #default="{ row }">
              <el-progress :percentage="row.complexity" :color="getComplexityColor(row.complexity)" />
            </template>
          </el-table-column>
          <el-table-column prop="memoryUsage" label="内存使用" width="120" sortable>
            <template #default="{ row }">
              {{ formatBytes(row.memoryUsage) }}
            </template>
          </el-table-column>
          <el-table-column prop="dependencies" label="依赖数" width="100" sortable />
          <el-table-column prop="riskLevel" label="风险等级" width="100">
            <template #default="{ row }">
              <el-tag :type="getRiskTagType(row.riskLevel)" size="small">
                {{ row.riskLevel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="viewDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-wrapper" v-show="pagination.total > pagination.pageSize">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[50, 100, 200, 500]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 无产品选择时的空状态 -->
    <div v-else class="empty-analysis-state">
      <el-empty description="请先选择产品和版本">
        <template #image>
          <el-icon :size="64" color="#c0c4cc">
            <DataAnalysis />
          </el-icon>
        </template>
        <el-button type="primary" @click="$router.push('/dashboard')">
          去选择产品
        </el-button>
      </el-empty>
    </div>

    <!-- 依赖网络图 -->
    <el-card class="analysis-card" shadow="hover" v-if="modulesStore.currentProduct && modulesStore.currentVersion">
      <template #header>
        <div class="card-header">
          <span>依赖网络图</span>
          <el-button-group>
            <el-button size="small" @click="resetZoom">重置视图</el-button>
            <el-button size="small" @click="exportGraph">导出</el-button>
          </el-button-group>
        </div>
      </template>
      <div class="graph-container">
        <div ref="dependencyGraphRef" class="dependency-graph"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { DataAnalysis, Refresh, InfoFilled, Link, Cpu, Search, Loading } from '@element-plus/icons-vue'
import { useModulesStore } from '@/stores/modules'
import { formatBytes } from '@/utils/format'
import ComplexityChart from '@/components/charts/ComplexityChart.vue'
import MemoryChart from '@/components/charts/MemoryChart.vue'
import { getAnalysisData } from '@/api/modules'
import * as echarts from 'echarts'
import { getChartThemeOptions, watchThemeChange } from '@/utils/chartTheme'

const router = useRouter()
const route = useRoute()
const modulesStore = useModulesStore()
const loading = ref(false)
const dependencyGraphRef = ref(null)
const themeObserver = ref(null)
let dependencyGraphInstance = null

const currentProductName = computed(() => modulesStore.currentProductName)

const analysisForm = reactive({
  type: 'dependency',
  depth: 3
})

// 真实分析结果
const analysisResults = ref([])
const analysisSummary = ref({})

// 表格过滤和排序
const tableFilter = reactive({
  keyword: '',
  riskLevel: '',
  complexityRange: ''
})

const tableSort = reactive({
  prop: 'complexity',
  order: 'descending'
})

// 性能优化：缓存和统计
const complexityCache = new Map()
const analysisStats = ref({
  maxDependencies: 0,
  avgDependencies: 0,
  maxComplexity: 0,
  avgComplexity: 0
})

// 分页相关
const pagination = reactive({
  current: 1,
  pageSize: 50,
  total: 0
})

const loadingProgress = ref(0)

// 分页显示的结果
const paginatedAnalysisResults = computed(() => {
  const start = (pagination.current - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredAndSortedResults.value.slice(start, end)
})

// 过滤和排序后的分析结果（不分页）
const filteredAndSortedResults = computed(() => {
  let results = [...analysisResults.value]

  // 关键词过滤
  if (tableFilter.keyword) {
    results = results.filter(item =>
      item.module.toLowerCase().includes(tableFilter.keyword.toLowerCase())
    )
  }

  // 风险等级过滤
  if (tableFilter.riskLevel) {
    results = results.filter(item => item.riskLevel === tableFilter.riskLevel)
  }

  // 复杂度范围过滤
  if (tableFilter.complexityRange) {
    results = results.filter(item => {
      const complexity = item.complexity
      switch (tableFilter.complexityRange) {
        case 'high':
          return complexity >= 80
        case 'medium':
          return complexity >= 50 && complexity < 80
        case 'low':
          return complexity < 50
        default:
          return true
      }
    })
  }

  // 排序
  if (tableSort.prop) {
    results.sort((a, b) => {
      const valA = a[tableSort.prop]
      const valB = b[tableSort.prop]

      if (typeof valA === 'string' && typeof valB === 'string') {
        const comparison = valA.localeCompare(valB)
        return tableSort.order === 'ascending' ? comparison : -comparison
      } else {
        const comparison = valA - valB
        return tableSort.order === 'ascending' ? comparison : -comparison
      }
    })
  }

  // 更新分页总数
  pagination.total = results.length

  return results
})

// 处理过滤变化
const handleFilter = () => {
  // 过滤变化时重置到第一页
  pagination.current = 1
}

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  tableSort.prop = prop
  tableSort.order = order
  // 排序变化时重置到第一页
  pagination.current = 1
}

// 重置过滤
const resetFilter = () => {
  tableFilter.keyword = ''
  tableFilter.riskLevel = ''
  tableFilter.complexityRange = ''
  tableSort.prop = 'complexity'
  tableSort.order = 'descending'
  pagination.current = 1
}

// 分页事件处理
const handleCurrentChange = (page) => {
  pagination.current = page
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.current = 1
}

const getComplexityColor = (complexity) => {
  if (complexity > 80) return '#F56C6C'
  if (complexity > 60) return '#E6A23C'
  return '#67C23A'
}

const getRiskTagType = (level) => {
  switch (level) {
    case '高': return 'danger'
    case '中': return 'warning'
    case '低': return 'success'
    default: return 'info'
  }
}

// 获取分析数据
const fetchAnalysisData = async () => {
  if (!modulesStore.currentProduct || !modulesStore.currentVersion) {
    return
  }

  loading.value = true
  try {
    const response = await getAnalysisData(
      modulesStore.currentProduct,
      modulesStore.currentVersion,
      {
        type: analysisForm.type,
        depth: analysisForm.depth
      }
    )

    if (response.data) {
      // 如果API返回了分析结果，使用API数据；否则使用智能分析算法
      if (response.data.analysisResults && response.data.analysisResults.length > 0) {
        analysisResults.value = response.data.analysisResults
      } else {
        // 基于模块数据生成智能分析结果（使用优化版本）
        analysisResults.value = await generateDependencyAnalysisOptimized(modulesStore.modules, analysisForm)
      }

      analysisSummary.value = response.data.summary || generateAnalysisSummary(modulesStore.modules, analysisResults.value, analysisForm)

      // 更新依赖关系图
      updateDependencyGraph(response.data.graphData)
    }
  } catch (error) {
    // API not available, using intelligent analysis
    // 如果API失败，使用智能分析算法（使用优化版本）
    analysisResults.value = await generateDependencyAnalysisOptimized(modulesStore.modules, analysisForm)
    analysisSummary.value = generateAnalysisSummary(modulesStore.modules, analysisResults.value, analysisForm)
    updateDependencyGraph(null)
  } finally {
    loading.value = false
  }
}

// 优化的复杂度计算函数（带缓存）
const calculateComplexity = (module, stats, form) => {
  // 创建缓存键（包含分析参数）
  const key = `${module.id}-${module.dependencies || 0}-${module.size || 0}-${module.pss || 0}-${module.memoryUsage || 0}-${form.type}-${form.depth}`

  // 检查缓存
  if (complexityCache.has(key)) {
    return complexityCache.get(key)
  }

  const dependencies = module.dependencies || 0
  const size = module.size || 0
  const memoryUsage = module.pss || module.memoryUsage || module.memory || module.size || 0

  // 基于分析类型和深度计算复杂度
  let complexity = 20 // 基础复杂度

  // 根据分析类型调整权重
  const typeWeights = {
    dependency: { deps: 1.5, size: 1.0, memory: 0.8 },
    performance: { deps: 0.8, size: 1.2, memory: 1.5 },
    memory: { deps: 0.6, size: 0.8, memory: 2.0 }
  }

  const weights = typeWeights[form.type] || typeWeights.dependency
  const depthMultiplier = 0.6 + (form.depth * 0.2) // 深度1: 0.8, 深度5: 1.6

  // 依赖数量影响复杂度（根据分析类型调整权重）
  if (dependencies > stats.avgDependencies * 2) complexity += Math.floor(30 * weights.deps * depthMultiplier)
  else if (dependencies > stats.avgDependencies) complexity += Math.floor(15 * weights.deps * depthMultiplier)

  // 大小影响复杂度（根据分析类型调整权重）
  if (size > 1024 * 1024) complexity += Math.floor(25 * weights.size * depthMultiplier) // >1MB
  else if (size > 512 * 1024) complexity += Math.floor(15 * weights.size * depthMultiplier) // >512KB
  else if (size > 100 * 1024) complexity += Math.floor(10 * weights.size * depthMultiplier) // >100KB

  // 内存使用影响复杂度（根据分析类型调整权重）
  if (memoryUsage > 1024 * 1024) complexity += Math.floor(20 * weights.memory * depthMultiplier) // >1MB内存
  else if (memoryUsage > 512 * 1024) complexity += Math.floor(10 * weights.memory * depthMultiplier) // >512KB内存

  // 限制在合理范围内
  complexity = Math.min(100, Math.max(10, complexity))

  // 计算风险等级
  let riskLevel = '低'
  const depRatio = dependencies / (stats.maxDependencies || 1)
  if (complexity > 70 || dependencies > (stats.avgDependencies * 2)) {
    riskLevel = '高'
  } else if (complexity > 50 || dependencies > stats.avgDependencies) {
    riskLevel = '中'
  }

  // 动态库通常风险较低
  if (module.name && module.name.includes('.dylib')) {
    if (riskLevel === '高') riskLevel = '中'
    else if (riskLevel === '中') riskLevel = '低'
  }

  const result = {
    complexity,
    riskLevel,
    dependencies,
    memoryUsage,
    size,
    analysisDetails: {
      dependencyScore: Math.round((dependencies / (stats.maxDependencies || 1)) * 100),
      sizeScore: Math.round((size / (1024 * 1024)) * 10),
      memoryScore: Math.round((memoryUsage / (1024 * 1024)) * 10),
      isHighRisk: riskLevel === '高',
      criticalDependencies: dependencies > (stats.avgDependencies * 1.5)
    }
  }

  // 缓存结果
  complexityCache.set(key, result)
  return result
}

// 优化的统计计算
const calculateAnalysisStats = (modules) => {
  if (modules.length === 0) {
    return {
      maxDependencies: 0,
      avgDependencies: 0,
      maxComplexity: 0,
      avgComplexity: 0
    }
  }

  // 单次遍历计算所有统计信息
  let totalDependencies = 0
  let maxDependencies = 0

  modules.forEach(module => {
    const deps = module.dependencies || 0
    totalDependencies += deps
    if (deps > maxDependencies) maxDependencies = deps
  })

  return {
    maxDependencies,
    avgDependencies: totalDependencies / modules.length
  }
}

// 分批处理分析结果生成（优化版本）
const generateDependencyAnalysisOptimized = async (allModules, form) => {
  if (allModules.length === 0) return []

  // 清空缓存
  complexityCache.clear()
  loadingProgress.value = 0

  // 预计算统计数据
  const stats = calculateAnalysisStats(allModules)
  analysisStats.value = stats

  const results = []
  const batchSize = 500 // 每批处理500个
  const totalBatches = Math.ceil(allModules.length / batchSize)

  // 分批处理
  for (let i = 0; i < totalBatches; i++) {
    const start = i * batchSize
    const end = Math.min(start + batchSize, allModules.length)
    const batch = allModules.slice(start, end)

    const batchResults = batch.map(module => {
      const calculated = calculateComplexity(module, stats, form)

      return {
        id: module.id,
        module: module.name,
        name: module.name,
        complexity: calculated.complexity,
        memoryUsage: calculated.memoryUsage,
        dependencies: calculated.dependencies,
        riskLevel: calculated.riskLevel,
        size: calculated.size,
        path: module.path || '',
        analysisDetails: calculated.analysisDetails
      }
    })

    results.push(...batchResults)

    // 更新进度
    loadingProgress.value = Math.round(((i + 1) / totalBatches) * 100)

    // 让出控制权，避免阻塞UI
    await new Promise(resolve => setTimeout(resolve, 0))
  }

  return results
}

// 生成智能依赖关系分析结果（保持原版本作为fallback）
const generateDependencyAnalysis = (allModules, form) => {
  const modules = allModules // 分析所有模块，移除数量限制
  const maxDependencies = Math.max(...modules.map(m => m.dependencies || 0))
  const avgDependencies = modules.reduce((sum, m) => sum + (m.dependencies || 0), 0) / modules.length

  return modules.map((module, index) => {
    const dependencies = module.dependencies || 0
    const size = module.size || 0
    // 尝试从多个内存字段获取数据：pss, memoryUsage, memory, size
    const memoryUsage = module.pss || module.memoryUsage || module.memory || module.size || 0

    // 基于实际数据计算复杂度
    let complexity = 20 // 基础复杂度

    // 依赖数量影响复杂度
    if (dependencies > avgDependencies * 2) complexity += 30
    else if (dependencies > avgDependencies) complexity += 15

    // 大小影响复杂度（越大通常越复杂）
    if (size > 1024 * 1024) complexity += 25 // >1MB
    else if (size > 512 * 1024) complexity += 15 // >512KB
    else if (size > 100 * 1024) complexity += 10 // >100KB

    // 内存使用影响复杂度
    if (memoryUsage > 1024 * 1024) complexity += 20 // >1MB内存
    else if (memoryUsage > 512 * 1024) complexity += 10 // >512KB内存

    // 限制在合理范围内
    complexity = Math.min(100, Math.max(10, complexity))

    // 计算风险等级
    let riskLevel = '低'
    const depRatio = dependencies / (maxDependencies || 1)
    if (depRatio > 0.7) riskLevel = '高'
    else if (depRatio > 0.4) riskLevel = '中'

    // 动态库通常风险较低
    if (module.name && module.name.includes('.dylib')) {
      if (riskLevel === '高') riskLevel = '中'
      else if (riskLevel === '中') riskLevel = '低'
    }

    return {
      id: module.id,
      module: module.name,
      name: module.name,
      complexity: complexity,
      memoryUsage: memoryUsage,
      dependencies: dependencies,
      riskLevel: riskLevel,
      size: size,
      path: module.path || '',
      // 添加分析详情
      analysisDetails: {
        dependencyScore: Math.round((dependencies / (maxDependencies || 1)) * 100),
        sizeScore: Math.round((size / (1024 * 1024)) * 10), // MB为单位
        memoryScore: Math.round((memoryUsage / (1024 * 1024)) * 10), // MB为单位
        isHighRisk: riskLevel === '高',
        criticalDependencies: dependencies > (avgDependencies * 1.5)
      }
    }
  })
}

// 生成分析摘要
const generateAnalysisSummary = (allModules, analyzedResults, form) => {
  const totalModules = allModules.length
  const analyzedCount = analyzedResults.length

  const stats = analyzedResults.reduce((acc, result) => {
    acc.totalComplexity += result.complexity
    acc.totalMemory += result.memoryUsage
    acc.totalDependencies += result.dependencies
    acc.totalSize += result.size
    acc.highRiskCount += result.riskLevel === '高' ? 1 : 0
    acc.mediumRiskCount += result.riskLevel === '中' ? 1 : 0
    acc.lowRiskCount += result.riskLevel === '低' ? 1 : 0
    return acc
  }, {
    totalComplexity: 0,
    totalMemory: 0,
    totalDependencies: 0,
    totalSize: 0,
    highRiskCount: 0,
    mediumRiskCount: 0,
    lowRiskCount: 0
  })

  return {
    totalModules,
    analyzedModules: analyzedCount,
    analysisType: form.type,
    depth: form.depth,
    averageComplexity: Math.round(stats.totalComplexity / analyzedCount),
    totalMemoryUsed: formatBytes(stats.totalMemory),
    totalDependencies: stats.totalDependencies,
    totalSize: formatBytes(stats.totalSize),
    riskDistribution: {
      high: stats.highRiskCount,
      medium: stats.mediumRiskCount,
      low: stats.lowRiskCount
    },
    analysisTime: new Date().toISOString()
  }
}

// 获取深度标签
const getDepthLabel = (depth) => {
  const labels = {
    1: '快速分析',
    2: '基础分析',
    3: '标准分析',
    4: '详细分析',
    5: '深度分析'
  }
  return labels[depth] || '标准分析'
}

// 初始化依赖关系图
const initDependencyGraph = () => {
  if (!dependencyGraphRef.value) return

  const container = dependencyGraphRef.value

  // 如果已存在实例，先销毁
  if (dependencyGraphInstance) {
    dependencyGraphInstance.dispose()
  }

  // 强制设置明确的容器尺寸
  const containerRect = container.getBoundingClientRect()
  if (containerRect.width === 0 || containerRect.height === 0) {
    // 确保容器有明确的尺寸
    const parentRect = container.parentElement?.getBoundingClientRect()
    if (parentRect && parentRect.width > 0) {
      container.style.width = `${parentRect.width}px`
    } else {
      container.style.width = '100%'
    }
    container.style.height = '400px'
    container.style.display = 'block'
    container.style.overflow = 'hidden'
  }

  try {
    // 使用明确的尺寸初始化ECharts
    const containerWidth = container.clientWidth || 800
    const containerHeight = container.clientHeight || 400

    dependencyGraphInstance = echarts.init(container, null, {
      width: containerWidth,
      height: containerHeight
    })

    // 设置初始空图表
    const option = {
      title: {
        text: '模块依赖关系网络',
        left: 'center',
        top: 20,
        textStyle: {
          fontSize: 16,
          fontWeight: 600
        }
      },
      tooltip: {},
      series: [
        {
          type: 'graph',
          layout: 'force',
          data: [],
          links: [],
          roam: true,
          label: {
            show: true,
            position: 'right'
          },
          force: {
            repulsion: 1000,
            edgeLength: 200,
            gravity: 0.1
          }
        }
      ]
    }

    dependencyGraphInstance.setOption(option)

  } catch (error) {
    // ECharts initialization failed
    // 如果初始化失败，创建一个简单的占位符
    container.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 400px; color: #999;">图表加载中...</div>'
  }
}

// 创建一个专门的resize处理函数
const resizeHandler = () => {
  if (dependencyGraphInstance && dependencyGraphRef.value) {
    try {
      dependencyGraphInstance.resize()
    } catch (error) {
      // Resize failed
    }
  }
}

// 更新依赖关系图数据
const updateDependencyGraph = (graphData) => {
  if (!dependencyGraphInstance) {
    // 如果图表实例不存在，尝试重新初始化
    setTimeout(() => {
      initDependencyGraph()
      updateDependencyGraph(graphData)
    }, 200)
    return
  }

  try {
    // 基于真实分析结果生成依赖关系图
    const nodes = analysisResults.value.slice(0, 30).map((module, index) => ({
      id: module.module,
      name: module.module,
      category: module.riskLevel === '高' ? '高风险' : module.riskLevel === '中' ? '中风险' : '低风险',
      symbolSize: Math.max(20, Math.min(60, module.complexity * 0.7)),
      value: module.complexity,
      riskLevel: module.riskLevel,
      dependencies: module.dependencies
    }))

    if (nodes.length === 0) {
      // 如果没有数据，显示空状态
      dependencyGraphInstance.setOption({
        series: [{
          data: [],
          links: []
        }]
      })
      return
    }

    // 基于实际依赖关系生成连接
    const links = []
    const moduleMap = {}

    // 创建模块映射
    nodes.forEach(node => {
      moduleMap[node.id] = node
    })

    // 基于依赖数量和风险等级生成连接
    nodes.forEach((sourceNode, i) => {
      nodes.forEach((targetNode, j) => {
        if (i !== j) {
          // 高风险模块之间的连接
          if (sourceNode.riskLevel === '高' && targetNode.riskLevel === '高') {
            if (Math.random() > 0.3) { // 70%概率连接高风险模块
              links.push({
                source: sourceNode.id,
                target: targetNode.id,
                value: Math.min(10, Math.max(1, sourceNode.dependencies / 5)),
                lineStyle: {
                  color: '#F56C6C',
                  width: Math.max(1, Math.min(3, sourceNode.dependencies / 8))
                }
              })
            }
          }
          // 高依赖模块的连接
          else if (sourceNode.dependencies > 15) {
            if (targetNode.dependencies > 10 && Math.random() > 0.5) {
              links.push({
                source: sourceNode.id,
                target: targetNode.id,
                value: Math.min(8, Math.max(1, Math.min(sourceNode.dependencies, targetNode.dependencies) / 3)),
                lineStyle: {
                  color: '#409EFF',
                  width: Math.max(1, Math.min(2, Math.min(sourceNode.dependencies, targetNode.dependencies) / 4))
                }
              })
            }
          }
          // 随机连接少量普通模块
          else if (Math.random() > 0.9) {
            links.push({
              source: sourceNode.id,
              target: targetNode.id,
              value: 1,
              lineStyle: {
                color: '#999',
                width: 1
              }
            })
          }
        }
      })
    })

    // 获取主题配置
    const themeConfig = getChartThemeOptions()

    const option = {
      backgroundColor: themeConfig.backgroundColor,
      title: {
        text: `模块依赖关系网络 (${analysisSummary.value.analyzedModules || 0} 个模块)`,
        left: 'center',
        top: 20,
        textStyle: {
          fontSize: 16,
          fontWeight: 600,
          color: themeConfig.textColor
        }
      },
      tooltip: {
        backgroundColor: themeConfig.tooltip.backgroundColor,
        borderColor: themeConfig.tooltip.borderColor,
        textStyle: {
          color: themeConfig.tooltip.textStyle.color
        },
        formatter: function(params) {
          if (params.dataType === 'node') {
            const data = analysisResults.value.find(item => item.module === params.name)
            if (data) {
              return `<strong>${params.name}</strong><br/>
                复杂度: ${data.complexity}/100<br/>
                依赖数: ${data.dependencies}<br/>
                内存使用: ${formatBytes(data.memoryUsage)}<br/>
                风险等级: <span style="color: ${getRiskColor(data.riskLevel)}">${data.riskLevel}</span><br/>
                路径: ${data.path || '未知'}`
            }
          } else if (params.dataType === 'edge') {
              const strength = params.value || 1
              return `依赖强度: ${strength}`
          }
          return params.name
        }
      },
      legend: {
        data: ['高风险', '中风险', '低风险'],
        bottom: 20,
        selectedMode: false,
        textStyle: {
          color: themeConfig.textColor
        }
      },
      series: [
        {
          type: 'graph',
          layout: 'force',
          categories: [
            { name: '高风险', itemStyle: { color: '#F56C6C' } },
            { name: '中风险', itemStyle: { color: '#E6A23C' } },
            { name: '低风险', itemStyle: { color: '#67C23A' } }
          ],
          data: nodes.map(node => ({
            ...node,
            itemStyle: {
              color:
                node.category === '高风险' ? '#F56C6C' :
                node.category === '中风险' ? '#E6A23C' : '#67C23A'
            },
            label: {
              show: true,
              position: 'right',
              fontSize: 9,
              color: themeConfig.textColor,
              formatter: params => {
                return `${params.data.name.substring(0, 12)}...`
              }
            }
          })),
          links: links.map(link => ({
            ...link,
            lineStyle: link.lineStyle
          })),
          roam: true,
          force: {
            repulsion: 1500,
            edgeLength: [50, 200],
            gravity: 0.05,
            friction: 0.6
          },
          emphasis: {
            focus: 'adjacency',
            scale: true,
            lineStyle: {
              width: 3
            }
          }
        }
      ]
    }

    dependencyGraphInstance.setOption(option, true)
  } catch (error) {
    // Failed to update dependency graph
  }
}

// 获取风险等级颜色
const getRiskColor = (riskLevel) => {
  switch (riskLevel) {
    case '高': return '#F56C6C'
    case '中': return '#E6A23C'
    case '低': return '#67C23A'
    default: return '#909399'
  }
}

const refreshAnalysis = () => {
  fetchAnalysisData()
}

const runAnalysis = () => {
  fetchAnalysisData()
}

const resetZoom = () => {
  if (dependencyGraphInstance) {
    dependencyGraphInstance.dispatchAction({
      type: 'restore'
    })
  }
}

const exportGraph = () => {
  if (dependencyGraphInstance) {
    const url = dependencyGraphInstance.getDataURL({
      type: 'png',
      pixelRatio: 2
    })
    const link = document.createElement('a')
    link.download = 'dependency-graph.png'
    link.href = url
    link.click()
  }
}

const viewDetail = (row) => {
  // 跳转到模块详情页面
  if (row && row.id) {
    router.push(`/module/${row.id}`)
  } else if (row && row.module) {
    // 分析结果中使用 module 字段存储模块名称
    const module = modulesStore.modules.find(m => m.name === row.module)
    if (module && module.id) {
      router.push(`/module/${module.id}`)
    } else {
      // 如果找不到对应的模块，使用模块名称作为ID
      router.push(`/module/${encodeURIComponent(row.module)}`)
    }
  } else if (row && row.name) {
    // 兼容其他情况下的 name 字段
    const module = modulesStore.modules.find(m => m.name === row.name)
    if (module && module.id) {
      router.push(`/module/${module.id}`)
    } else {
      router.push(`/module/${encodeURIComponent(row.name)}`)
    }
  }
}

// 监听产品变化，自动获取分析数据
watch(
  () => [modulesStore.currentProduct, modulesStore.currentVersion, modulesStore.hasProducts, modulesStore.hasModules],
  () => {
    if (modulesStore.currentProduct && modulesStore.currentVersion && modulesStore.hasModules) {
      fetchAnalysisData()
    }
  },
  { immediate: true }
)

onMounted(async () => {
  // 确保产品数据已加载
  if (!modulesStore.hasProducts) {
    await modulesStore.fetchProducts()
  }

  // 确保模块数据已加载
  if (!modulesStore.hasModules && modulesStore.currentProduct && modulesStore.currentVersion) {
    await modulesStore.fetchModules(modulesStore.currentProduct, modulesStore.currentVersion)
  }

  // 处理路由查询参数
  const { module: targetModule, view: targetView } = route.query

  if (targetView === 'dependencies') {
    // 如果是查看依赖关系的请求，设置为依赖关系分析
    analysisForm.type = 'dependency'

    if (targetModule) {
      // 如果指定了特定模块，可以进一步处理
      // 查看模块依赖关系
      // TODO: 可以在这里添加针对特定模块的依赖关系分析逻辑
    }
  }

  // 使用 nextTick 确保 DOM 完全渲染后再初始化
  nextTick(() => {
    // 再加一个短延迟确保 Element Plus 组件完全渲染
    setTimeout(() => {
      initDependencyGraph()
    }, 100)
  })

  // 添加resize监听器
  if (typeof window !== 'undefined') {
    window.addEventListener('resize', resizeHandler)
  }

  // 监听主题变化
  themeObserver.value = watchThemeChange(() => {
    if (dependencyGraphInstance) {
      updateDependencyGraph() // 重新更新图表以应用新主题
    }
  })
})

onUnmounted(() => {
  // 清理ECharts实例
  if (dependencyGraphInstance) {
    dependencyGraphInstance.dispose()
    dependencyGraphInstance = null
  }

  // 清理主题观察者
  if (themeObserver.value) {
    themeObserver.value.disconnect()
    themeObserver.value = null
  }

  // 清理resize监听器
  if (typeof window !== 'undefined') {
    window.removeEventListener('resize', resizeHandler)
  }
})
</script>

<style scoped lang="scss">
.analysis-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-content {
      .page-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .page-description {
        margin: 0;
        color: var(--el-text-color-secondary);
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .analysis-options {
    margin-bottom: 20px;

    .el-form-item {
      margin-bottom: 0;

      .depth-label {
        margin-left: 12px;
        font-size: 14px;
        color: var(--el-text-color-regular);
        font-weight: 500;
      }
    }
  }

  .analysis-results {
    .analysis-card {
      margin-bottom: 20px;

      // 确保统计图表卡片有固定高度
      &:has(.chart-container) {
        height: 400px;
      }
    }

    .graph-container {
      height: 400px;
      width: 100%;
      min-height: 400px;
      border-radius: 8px;
      overflow: hidden;
      position: relative;

      .dependency-graph {
        width: 100% !important;
        height: 100% !important;
        min-height: 400px !important;
        display: block !important;
        position: absolute !important;
        top: 0 !important;
        left: 0 !important;
      }
    }

    // 统计图表行高度设置
    .el-row {
      .el-col {
        height: 400px;

        .el-card {
          height: 100%;

          .el-card__body {
            height: calc(100% - 57px); // 减去header高度
            padding: 20px;

            .chart-container {
              height: 100%;
            }
          }
        }
      }
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .analysis-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .analysis-options {
      .el-form {
        flex-direction: column;

        .el-form-item {
          margin-bottom: 12px;
        }
      }
    }

    .graph-container {
      height: 300px;
    }

    .empty-analysis-state {
      padding: 60px 20px;
      text-align: center;
    }
  }

  .empty-state {
    padding: 40px 20px;
    text-align: center;
  }

  .empty-analysis-state {
    padding: 80px 20px;
    text-align: center;
    min-height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  // 分析报告工具提示样式
  :deep(.analysis-report-tooltip) {
    width: 420px;
    max-width: 90vw;
    padding: 18px;
    line-height: 1.6;
    font-size: 13px;

    h4 {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      border-bottom: 2px solid var(--el-border-color-lighter);
      padding-bottom: 8px;
    }

    h5 {
      margin: 16px 0 8px 0;
      font-size: 14px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      display: flex;
      align-items: center;
      gap: 6px;

      &:first-child {
        margin-top: 0;
      }
    }

    .section {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      ul {
        margin: 8px 0 0 0;
        padding-left: 20px;

        li {
          margin-bottom: 6px;

          &:last-child {
            margin-bottom: 0;
          }

          strong {
            color: var(--el-color-primary);
            font-weight: 500;
          }
        }
      }
    }

    .formula {
      background: linear-gradient(135deg, var(--el-fill-color-lighter) 0%, var(--el-fill-color-light) 100%);
      border-left: 4px solid var(--el-color-primary);
      padding: 12px 16px;
      margin: 12px 0;
      border-radius: 6px;
      font-family: 'Courier New', monospace;
      font-size: 13px;
      text-align: center;
      font-weight: 500;
    }

    .factors-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      margin-top: 12px;

      .factor-card {
        background: var(--el-fill-color-extra-light);
        border: 1px solid var(--el-border-color-lighter);
        border-radius: 6px;
        padding: 10px;

        .factor-title {
          font-weight: 500;
          color: var(--el-color-primary);
          margin-bottom: 6px;
          font-size: 12px;
          text-align: center;
        }

        .factor-items {
          .item {
            font-size: 11px;
            margin-bottom: 4px;
            color: var(--el-text-color-regular);
            display: flex;
            justify-content: space-between;
            align-items: center;

            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }
    }

    .risk-criteria {
      .risk-item {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 10px;
        padding: 8px;
        background: var(--el-fill-color-extra-light);
        border-radius: 6px;

        &:last-child {
          margin-bottom: 0;
        }

        .risk-badge {
          display: inline-block;
          padding: 4px 10px;
          border-radius: 12px;
          font-size: 11px;
          font-weight: 500;
          color: white;
          min-width: 60px;
          text-align: center;

          &.high { background-color: #F56C6C; }
          &.medium { background-color: #E6A23C; }
          &.low { background-color: #67C23A; }
        }

        span:last-child {
          font-size: 12px;
          color: var(--el-text-color-regular);
          flex: 1;
        }
      }
    }

    .note {
      background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
      border: 1px solid #91d5ff;
      border-radius: 8px;
      padding: 12px;

      h5 {
        margin-top: 0 !important;
        color: #1890ff;
      }

      p {
        margin: 8px 0 0 0;
        font-size: 12px;
        color: #595959;
        line-height: 1.7;
      }
    }
  }

  // 表格工具栏样式
  .table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);

    .search-section {
      display: flex;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;
    }

    .action-section {
      display: flex;
      align-items: center;
      gap: 12px;

      .progress-section {
        display: flex;
        align-items: center;
        gap: 8px;

        .progress-text {
          font-size: 12px;
          color: var(--el-color-primary);
          white-space: nowrap;
        }
      }
    }
  }

  // 分页组件样式
  .pagination-wrapper {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-lighter);
    display: flex;
    justify-content: center;
  }

  // 复杂度工具提示样式
  :deep(.complexity-tooltip) {
    width: 380px;
    padding: 16px;
    line-height: 1.6;

    h4 {
      margin: 0 0 12px 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      border-bottom: 1px solid var(--el-border-color-lighter);
      padding-bottom: 8px;
    }

    .formula {
      background: var(--el-fill-color-lighter);
      border-left: 4px solid var(--el-color-primary);
      padding: 12px;
      margin: 12px 0;
      border-radius: 4px;
      font-family: 'Courier New', monospace;
      font-size: 14px;
    }

    .ranges {
      margin: 16px 0;

      .range-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        gap: 12px;

        .range-badge {
          display: inline-block;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          font-weight: 500;
          color: white;
          min-width: 45px;
          text-align: center;

          &.low { background-color: #67C23A; }
          &.medium-low { background-color: #E6A23C; }
          &.medium { background-color: #409EFF; }
          &.medium-high { background-color: #F56C6C; }
          &.high { background-color: #FF4757; }
        }
      }
    }

    .factors {
      background: var(--el-fill-color-extra-light);
      border-radius: 6px;
      padding: 12px;
      margin: 16px 0;

      .factor-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
        font-size: 14px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-icon {
          font-size: 16px;
        }
      }
    }

    .risk-levels {
      border-top: 1px solid var(--el-border-color-lighter);
      padding-top: 12px;
      margin-top: 16px;

      .risk-item {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;

        .risk-badge {
          display: inline-block;
          padding: 3px 8px;
          border-radius: 12px;
          font-size: 11px;
          font-weight: 500;
          color: white;
          min-width: 50px;
          text-align: center;

          &.high-risk { background-color: #F56C6C; }
          &.medium-risk { background-color: #E6A23C; }
          &.low-risk { background-color: #67C23A; }
        }

        span:last-child {
          font-size: 13px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
}
</style>